﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lapas.Common.Forms;
//using Lapas.Common;
using WorkDAL;
using Lapas.Controls;
using System.Globalization;
using System.Threading;
using Common;
using Lapas.Common;

namespace WorksList
{
    public partial class WorkList : ListForm
    {
        public NotifyIcon noty = new NotifyIcon();
        public WorkList()
        {
            InitializeComponent();

            //CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
            //culture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
            //culture.DateTimeFormat.LongDatePattern = "dd MMMM, yyyy";
            //Thread.CurrentThread.CurrentCulture = culture;

            this.mainToolStrip.Items[3].Visible = false;
            //this.MaximizeBox = false;
            //this.MinimizeBox = true;

            timer1.Interval = 50000;
            timer1.Enabled = true;
            
            timer1.Tick += new EventHandler(OnTimerEvent);
        }

        private void OnTimerEvent(object source, EventArgs e)
        {
            ShowNotify();
        }

        private void ShowNotify()
        {
            try
            {
                if (noty.Visible == true)
                    noty.Visible = false;

            
                status = tscbStatus.ComboBox.SelectedValue.ToString();

                List<Work> worklist = WorksDataAccess.Instance().GetWorkList((DateTime?)openDate.Value, (DateTime?)endDate.Value, (DateTime?)expectedDate.Value, status, CommonSettings.UserName);

                string notymessage = string.Empty;

                notymessage = string.Format("Có {0} công việc chưa thực hiện hoặc đang thực hiện", worklist.Where(c => "O,P".Contains(c.Status)).Count().ToString()) + "\n";
                notymessage = notymessage + string.Format("Có {0} công việc chưa thực hiện", worklist.Where(c => c.Status.ToString().Contains("O")).Count().ToString()) + "\n";
                notymessage = notymessage + string.Format("Có {0} công việc đang thực hiện", worklist.Where(c => c.Status.ToString().Contains("P")).Count().ToString()) + "\n";
                notymessage = notymessage + string.Format("Có {0} công việc sẽ thực hiện sau", worklist.Where(c => c.Status.ToString().Contains("L")).Count().ToString()) + "\n";
                notymessage = notymessage + string.Format("Có {0} công việc đã hoàn thành", worklist.Where(c => c.Status.ToString().Contains("E")).Count().ToString()) + "\n";
                notymessage = notymessage + string.Format("Có {0} công việc đã xóa", worklist.Where(c => c.Status.ToString().Contains("X")).Count().ToString()) + "\n";

                noty.BalloonTipText = notymessage;
                noty.BalloonTipTitle = "Công việc thực hiện";
                noty.Icon = new Icon("Icon\\cal.ico");
                noty.Visible = true;
                noty.ShowBalloonTip(3);
            }
            catch (Exception ex)
            {
                Lapas.Common.DisplayMessage.ShowError(ex.ToString());
            }

            
        }

        private NullableDateTimePicker openDate, endDate, expectedDate;
        private ContextMenuStrip ms = new ContextMenuStrip();
        string status;
        
        protected override DataGridView Grid
        {
            get
            {
                return this.mainGrid;
            }
        }

        protected override void FormatGrid()
        {
            Lapas.Common.UIFormat.FormatGrid(mainGrid, true, true, true, false);
            Lapas.Common.UIFormat.SetGridColumnFormat(OpenDateCol, Lapas.Common.FormatType.Date);
            Lapas.Common.UIFormat.SetGridColumnFormat(ExpectedDateCol, Lapas.Common.FormatType.Date);
            Lapas.Common.UIFormat.SetGridColumnFormat(EndDateCol, Lapas.Common.FormatType.Date);
            Lapas.Common.UIFormat.SetGridColumnFormat(TitleCol, Lapas.Common.FormatType.NormalText);
        }

        private void GetData()
        {
            try
            {
                status = tscbStatus.ComboBox.SelectedValue.ToString();

                List<Work> worklist = WorksDataAccess.Instance().GetWorkList((DateTime?)openDate.Value, (DateTime?)endDate.Value, (DateTime?)expectedDate.Value, status, CommonSettings.UserName);
                bindingSource.DataSource = Convert2SortedBindingList(worklist);
                mainGrid.DataSource = bindingSource;
                BindData();

                linkLabel1.Text = string.Format("Có {0} công việc chưa thực hiện hoặc đang thực hiện", worklist.Where(c => "O,P".Contains(c.Status)).Count().ToString());
                linkLabel2.Text = string.Format("Có {0} công việc chưa thực hiện", worklist.Where(c => c.Status.ToString().Contains("O")).Count().ToString());
                linkLabel3.Text = string.Format("Có {0} công việc đang thực hiện", worklist.Where(c => c.Status.ToString().Contains("P")).Count().ToString());
                linkLabel4.Text = string.Format("Có {0} công việc sẽ thực hiện sau", worklist.Where(c => c.Status.ToString().Contains("L")).Count().ToString());
                linkLabel5.Text = string.Format("Có {0} công việc đã hoàn thành", worklist.Where(c => c.Status.ToString().Contains("E")).Count().ToString());
                linkLabel6.Text = string.Format("Có {0} công việc đã xóa", worklist.Where(c => c.Status.ToString().Contains("X")).Count().ToString());
            }
            catch(Exception ex)
            {
                Lapas.Common.DisplayMessage.ShowError(ex.ToString());
            }
        }

        protected override void BindData()
        {
            base.BindData();
        }

        private void WorkList_Load(object sender, EventArgs e)
        {
            CreateToolStrip();
            this.GetData();
            ShowNotify();
        }

        private void stbFind_Click(object sender, EventArgs e)
        {
            this.GetData();
        }

        private SortedBindingList<WorkObject> Convert2SortedBindingList(List<Work> worklist)
        {
            Lapas.Common.SortedBindingList<WorkObject> workObject = new SortedBindingList<WorkObject>(new List<WorkObject>());
            foreach (Work items in worklist)
            {
                WorkObject workitem = new WorkObject();
                workitem.Descriptions = items.Descriptions;
                workitem.EndDate = items.EndDate;
                workitem.ExpectedDate = items.ExpectedDate;
                workitem.ID = items.ID;
                workitem.OpenDate = items.OpenDate;
                workitem.Status =  items.Status;
                workitem.Title = items.Title;
                workitem.User = items.User;

                workObject.Add(workitem);
            }


            return workObject;
        }

        void CreateToolStrip()
        {
            try
            {
                openDate = UIFormat.Format_NullableDateTimePicker(openDate, DateTime.Today);
                toolStrip1.Items.Insert(1, new ToolStripControlHost(openDate));
                openDate.Value = null;

                expectedDate = UIFormat.Format_NullableDateTimePicker(expectedDate, DateTime.Today);
                toolStrip1.Items.Insert(3, new ToolStripControlHost(expectedDate));
                expectedDate.Value = null;

                endDate = UIFormat.Format_NullableDateTimePicker(endDate, DateTime.Today);
                toolStrip1.Items.Insert(5, new ToolStripControlHost(endDate));
                endDate.Value = null;

                ToolStripDropDownButton changeStatusBtn = new ToolStripDropDownButton("Chuyển trạng thái", Helper.GetBitmap("settingIcon"));
                //ContextMenuStrip ms = new ContextMenuStrip();
                List<TypeStatus> statustype = WorksDataAccess.Instance().GetTypes(string.Empty);
                foreach (TypeStatus item in statustype)
                {
                    string statusItem = item.Types.ToString() + " - " + item.Descriptions.Trim();
                    ms.Items.Add(new ToolStripMenuItem(statusItem, Helper.GetBitmap(item.Icon), ChangeStatusWork, item.Types));
                }
                changeStatusBtn.DropDown = ms;
                toolStrip1.Items.Add(changeStatusBtn);

                BindStatusType();

            }
            catch (Exception ex)
            {
                DisplayMessage.ShowError(ex.Message);
            }
        }

        private void ChangeStatusWork(object sender, EventArgs e)
        {
            Work work = new Work();
            if (DisplayMessage.ShowConfirm("Bạn muốn chuyển trạng thái công việc ?"))
            {
                foreach (DataGridViewRow row in mainGrid.SelectedRows)
                {
                    work.ID = (Guid)row.Cells[Id.Name].Value;

                    if (row.Cells[EndDateCol.Name].Value != null)
                        work.EndDate = (DateTime)row.Cells[EndDateCol.Name].Value;

                    WorksDataAccess.Instance().UpdateStatus(work, sender.ToString().Trim().Substring(0, 1));
                }
                GetData();
            }
        }


        void BindStatusType()
        {
            List<TypeStatus> statustype = WorksDataAccess.Instance().GetTypes(string.Empty);
            TypeStatus status = new TypeStatus();
            status.Types = "ALL";
            status.Descriptions = "<<Tất cả>>";
            
            statustype.Add(status);

            this.tscbStatus.ComboBox.DataSource = statustype;
            this.tscbStatus.ComboBox.DisplayMember = "Descriptions";
            this.tscbStatus.ComboBox.ValueMember = "Types";

            this.tscbStatus.ComboBox.SelectedIndex = statustype.Count() - 1;
        }

        #region linkLabel Click
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            List<Work> worklist = WorksDataAccess.Instance().GetWorkList(null, null, null, "O,P", CommonSettings.UserName);
            bindingSource.DataSource = Convert2SortedBindingList(worklist);
            mainGrid.DataSource = bindingSource;
            BindData();
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            List<Work> worklist = WorksDataAccess.Instance().GetWorkList(null, null, null, "O", CommonSettings.UserName);
            bindingSource.DataSource = Convert2SortedBindingList(worklist);
            mainGrid.DataSource = bindingSource;
            BindData();
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            List<Work> worklist = WorksDataAccess.Instance().GetWorkList(null, null, null, "P", CommonSettings.UserName);
            bindingSource.DataSource = Convert2SortedBindingList(worklist);
            mainGrid.DataSource = bindingSource;
            BindData();
        }

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            List<Work> worklist = WorksDataAccess.Instance().GetWorkList(null, null, null, "L", CommonSettings.UserName);
            bindingSource.DataSource = Convert2SortedBindingList(worklist);
            mainGrid.DataSource = bindingSource;
            BindData();
        }

        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            List<Work> worklist = WorksDataAccess.Instance().GetWorkList(null, null, null, "E", CommonSettings.UserName);
            bindingSource.DataSource = Convert2SortedBindingList(worklist);
            mainGrid.DataSource = bindingSource;
            BindData();
        }

        private void linkLabel6_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            List<Work> worklist = WorksDataAccess.Instance().GetWorkList(null, null, null, "X", CommonSettings.UserName);
            bindingSource.DataSource = Convert2SortedBindingList(worklist);
            mainGrid.DataSource = bindingSource;
            BindData();
        }
        #endregion

        protected override void DisplayEditForm(EditForm.EditFormAction action)
        {
            WorkEditForm workEditForm = new WorkEditForm();
            workEditForm.FormAction = action;

            if (action == EditForm.EditFormAction.Change)
            {
                workEditForm.workObject = (WorkObject)bindingSource.Current;
            }

            workEditForm.ShowDialog();
            if (workEditForm.Reload)
            {
                GetData();
            }
        }

        protected override void OnDelete(object sender, EventArgs e)
        {
            try
            {
                Guid id = new Guid();
                foreach (DataGridViewRow row in mainGrid.SelectedRows)
                {
                    id = (Guid)row.Cells[Id.Name].Value;
                    WorksDataAccess.Instance().DeleteWork(id);
                }
                this.GetData();
                DisplayMessage.ShowNotice("Đã xóa thành công bản ghi");
            }
            catch (Exception ex)
            {
                DisplayMessage.ShowError(ex.Message);
            }
        }

        private void mainGrid_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            foreach (DataGridViewRow row in mainGrid.SelectedRows)
            {
                if (row.Cells[TitleCol.Name].Value != null)
                    label1.Text = row.Cells[TitleCol.Name].Value.ToString();

                if (row.Cells[OpenDateCol.Name].Value != null)
                    label2.Text = "Ngày tạo: " + row.Cells[OpenDateCol.Name].Value.ToString();

                if (row.Cells[ExpectedDateCol.Name].Value != null)
                    label3.Text = "Ngày dự kiến hoàn thành: " + row.Cells[ExpectedDateCol.Name].Value.ToString();

                if (row.Cells[EndDateCol.Name].Value != null)
                    label4.Text = "Ngày hoàn thành: " + row.Cells[EndDateCol.Name].Value.ToString();
                else
                    label4.Text = "Ngày hoàn thành: ";

                if (row.Cells[StatusCol.Name].Value != null)
                    label5.Text = "Trạng thái: " + row.Cells[StatusCol.Name].Value.ToString();

                if (row.Cells[Descriptions.Name].Value != null)
                    label6.Text = "Nội dung: " + row.Cells[Descriptions.Name].Value.ToString();
            }
        }

        private void WorkList_FormClosed(object sender, FormClosedEventArgs e)
        {
            noty.Visible = false;
        }

    }
}
